package main

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/pflag"
	"qabx.net/common/utils/decode"
	logInit "qabx.net/common/utils/log"
	"qabx.net/safe-app-center/pkg/utils"
	"strings"
)

var (
	configRedisUrl        = pflag.String("safeAppCenterUrl", "192.168.28.211:6379", "security ability server listen")
	configRedisPassword   = pflag.String("redisPassword", "GTS0je4P65vy+Kt88ZOaZZCwLEu1wDhS7b0dLef0TkI=", "redis password")
	configRedisDB         = pflag.Int("redisDB", 1, "redis db")
	configFeatureFilePath = pflag.String("featureFilePath", "./resource/feature.cfg", "feature file path")
	configHeartCronTime   = pflag.Int64("heartCronTime", 0, "heart cron time")
	configType            = pflag.String("type", "", "app type")
	configVersion         = pflag.String("version", "", "app version")
	configLogLevelStr     = pflag.String("logLevelStr", "info", "log level str")
	configProvince        = pflag.String("province", "", "province")
)

var configLogger *log.Entry

func initRedis(redisUrl, redisPassword string, redisDB int) {
	logLevel, err := log.ParseLevel(*configLogLevelStr)
	if err != nil {
		fmt.Println("log level parse failed", err.Error())
		return
	}
	logInit.InitLogFile("safe-app-center", logLevel)
	mixStr, err := decode.GetDefaultMixStr()

	configLogger = log.WithFields(log.Fields{
		"app": "safe-app-center",
	})
	RedisAuth, err := decode.DecodeCBC(redisPassword, mixStr)

	fmt.Println(redisUrl, redisPassword, redisDB)
	err = utils.TTLOperator.InitClient(redisUrl, RedisAuth, redisDB)

	if err != nil {
		configLogger.Errorf("redis connect fail: %s", err.Error())
		return
	}
	return
}

func Feature(featureFilePath, version string) {
	fmt.Println("Feature start")

	// 输入参数校验
	if featureFilePath == "" || version == "" {
		fmt.Println("错误：无效的参数")
		return
	}

	// 假设 FeatureInit 返回 (bool, error)
	state := utils.FeatureInit(featureFilePath, version)

	if state {
		fmt.Println("feature success")
	} else {
		fmt.Println("feature fail")
	}
}

func HeartCronTime(heartCronTime int64, provinceCode string) {
	fmt.Println("HeartCronTime start")
	if heartCronTime == 0 {
		fmt.Println("heart cron time is zero")
		return
	}
	if provinceCode == "" {
		fmt.Println("province can't be nil")
		return
	}
	mapKey := fmt.Sprintf("edgeMap:%s", provinceCode)
	redisClient := utils.TTLOperator
	_ = redisClient.Hset(mapKey, "heartCronTime", fmt.Sprintf("%v", heartCronTime))
	fmt.Println("HeartCronTime set success")
	return
}

func main() {
	pflag.Parse()
	initRedis(*configRedisUrl, *configRedisPassword, *configRedisDB)
	fmt.Println("app_config start")
	configTypeStr := strings.Split(*configType, ",")
	for _, v := range configTypeStr {
		if v == "heartCronTime" {
			HeartCronTime(*configHeartCronTime, *configProvince)
		} else if v == "feature" {
			Feature(*configFeatureFilePath, *configVersion)
		}
	}

	fmt.Println("app_config finish")
}
